package srzy.socket

import srzy.rb._
import java.net.Socket
import java.net.InetSocketAddress
import srzy.common.Logging
import srzy.common.Config

abstract class RBSocketConn extends SocketConn {

  val pro: Protocol = RBProtocol

  def clientAuthentication = {
    logger.debug("authentication request")
    logger.info("ECRMsg : " + RBSocketConn.ECRMsg)
    write(RBSocketConn.ECRMsg)
    logger.debug("client authentication request write over!")
    val msg = read()
    val errCode = Integer.parseInt(getErrorCode(msg))
    if (errCode != 0) {
      throw new Exception("authentication failure : " + srzy.rb.getErrorCode(msg))
    }
    logger.info("ECAMsg : " + msg)
    logger.info("client authentication success")
  }

  def serverAuthentication = {
    logger.debug("authentication answer")
    val msg = read()
    logger.debug("ECRMsg : " + msg)
    logger.debug("server authentication answer read over!")
    logger.debug("ECAMsg : " + RBSocketConn.ECAMsg)
    write(RBSocketConn.ECAMsg)
    logger.info("server authentication success")

  }

  def replyHeartbeat = {
    write(RBSocketConn.KAAMsg.replaceAll(":TIME",
      srzy.common.Common.getSysTime("yyyyMMddhhmmssSS")))
    logger.debug("reply heartbeat")
  }

  def sendHeartbeat = {
    write(RBSocketConn.KARMsg.replaceAll(":TIME",
      srzy.common.Common.getSysTime("yyyyMMddhhmmssSS")))
    logger.debug("send heartbeat")
  }

  def write(msg: String) = {
    val b = RBMsg.pack(msg)
    writeLock.lock()
    try {
      outStream.write(b, 0, b.length)
      outStream.flush()
    } finally {
      writeLock.unlock()
    }
  }

  def read(): String = {
    readLock.lock()
    try {
      val header = this.read(RBMsg.rbHeaderLength)
      val body = this.read(RBMsg.getMsgBodyLen(header) - RBMsg.rbHeaderLength)
      RBMsg.getMsgBody(body)
    } finally {
      readLock.unlock()
    }
  }

}

object RBSocketConn extends Logging {

  val KARMsg = "[100=30][101=:TIME][210=192.168.168.7][210=172.168.1.248][003=0000]"
  val KAAMsg = "[100=31][101=:TIME][210=192.168.168.7][003=0]"

  val ECRMsg = "[100=01][101=20110421095919000][210=192.168.168.7][211=sa][212=123456]"
  val ECAMsg = "[100=02][101=20150407094419069][210=192.168.168.7][003=0]"

}
